package com.hainabo.mgcmall.api;

import com.hainabo.bootside.core.common.ReturnVO;
import com.hainabo.mgcmall.dao.DataDictOptionRepository;
import com.hainabo.mgcmall.dao.DataDictRepository;
import com.hainabo.mgcmall.model.DataDict;
import com.hainabo.mgcmall.model.DataDictOption;
import com.hainabo.mgcmall.util.DataTablePageUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.List;

@Api(value = "/v1/dataDict")
@Component
@Path("/v1/dataDict")
@Produces(MediaType.APPLICATION_JSON)
@Slf4j
public class DataDictResource {

	@Autowired
	DataDictRepository dataDictRepository;
	@Autowired
	DataDictOptionRepository optionRepository;
	@Autowired
	JdbcTemplate jdbcTemplate;

	// 查询字典列表
	@GET
	@Path("/list")
	public DataTablePageUtil list(@Context HttpServletRequest request) {
		DataTablePageUtil dataTablePageUtil = new DataTablePageUtil(request);
		String dictId = request.getParameter("dictId");
		String dictName = request.getParameter("dictName");
		String dictCode = request.getParameter("dictCode");
		String status = StringUtils.isNotBlank(request.getParameter("status")) ? request.getParameter("status") : "1";
		String start = request.getParameter("start");
		String length = request.getParameter("length");

		StringBuilder sb = new StringBuilder();
		sb.append(
				" SELECT t.dict_id dictId, t.dict_name dictName, t.dict_code dictCode, t.status FROM t_data_dict t WHERE 1 = 1");
		if (StringUtils.isNotBlank(dictId)) {
			sb.append(" AND t.dict_id = " + dictId);
		}
		if (StringUtils.isNotBlank(dictName)) {
			sb.append(" AND t.dict_name = " + dictName);
		}
		if (StringUtils.isNotBlank(dictCode)) {
			sb.append(" AND t.dict_code = " + dictCode);
		}
		if (StringUtils.isNotBlank(status)) {
			sb.append(" AND t.status = " + status);
		}
		sb.append(" ORDER BY t.dict_id");
		String countSql = "select count(*) totalNum from (" + sb.toString() + ") t";
		if (StringUtils.isNotBlank(start) && StringUtils.isNotBlank(length)) {
			sb.append(" limit " + start + "," + length);
		}
		List rows = jdbcTemplate.queryForList(sb.toString());
		dataTablePageUtil.setData(rows);
		int count = Integer.parseInt(jdbcTemplate.queryForList(countSql).get(0).get("totalNum").toString());
		dataTablePageUtil.setRecordsTotal(count);
		dataTablePageUtil.setRecordsFiltered(count);
		return dataTablePageUtil;
	}

	// 查询单个字典
	@GET
	@Path("/get/{dictId}")
	public ReturnVO findById(@PathParam(value = "dictId") Long dictId) {
		return new ReturnVO(dataDictRepository.findOne(dictId));
	}

	// 删除字典
	@DELETE
	@Path("/del/{dictId}")
	public ReturnVO del(@PathParam("dictId") Long dictId) {
		DataDict dataDict = dataDictRepository.findOne(dictId);
		if (dataDict != null) {
			dataDict.setStatus(-1);
			dataDictRepository.save(dataDict);
			return new ReturnVO("删除成功");
		} else {
			return new ReturnVO(false, "没有找到要删除的数据");
		}
	}

	// 保存字典
	@POST
	@Path("/save")
	public ReturnVO save(DataDict dataDict) {
		if (dataDict.getDictId() != null) { // 更新
			DataDict old = dataDictRepository.findOne(dataDict.getDictId());
			// 1.前端更改的是dictName
			if (dataDict.getDictName() != null) {
				List<DataDict> existList = dataDictRepository.findByDictName(dataDict.getDictName());
				if (existList.size() > 1
						|| (existList.size() == 1 && existList.get(0).getDictId() != dataDict.getDictId())) {
					return new ReturnVO(0, null, "已经存在相同的字典名称，请重新输入");
				}
				old.setDictName(dataDict.getDictName());// 只更新dictName
			}
			// 2.前端要更改的是dictCode
			if (dataDict.getDictCode() != null) {
				List<DataDict> existList = dataDictRepository.findByDictCode(dataDict.getDictCode());
				if (existList.size() > 1
						|| (existList.size() == 1 && existList.get(0).getDictId() != dataDict.getDictId())) {
					return new ReturnVO(0, null, "已经存在相同的字典编码，请重新输入");
				}
				old.setDictCode(dataDict.getDictCode());// 只更新dictCode
			}
			return new ReturnVO(dataDictRepository.save(old));
		} else { // 新增
			List<DataDict> existList = dataDictRepository.findByDictNameOrDictCode(dataDict.getDictName(),
					dataDict.getDictCode());
			if (!existList.isEmpty()) {
				return new ReturnVO(0, null, "已经存在相同的字典名称或者编码，请重新输入");
			}
			dataDict.setStatus(1);
			return new ReturnVO(dataDictRepository.save(dataDict));
		}
	}

	// 查询字典属性列表
	@GET
	@Path("/option/list/{dictId}")
	public DataTablePageUtil optionList(@Context HttpServletRequest request, @PathParam("dictId") Long dictId) {
		DataTablePageUtil dataTablePageUtil = new DataTablePageUtil(request);
		String optionId = request.getParameter("optionId");
		String optionName = request.getParameter("optionName");
		String optionValue = request.getParameter("optionValue");
		String status = StringUtils.isNotBlank(request.getParameter("status")) ? request.getParameter("status") : "1";
		String start = request.getParameter("start");
		String length = request.getParameter("length");

		StringBuilder sb = new StringBuilder();
		sb.append(
				" SELECT t.option_id optionId, t.option_name optionName, t.option_value optionValue, t.dict_id dictId FROM t_data_dict_option t WHERE 1=1");
		if (StringUtils.isNotBlank(optionId)) {
			sb.append(" AND t.option_id = " + optionId);
		}
		if (StringUtils.isNotBlank(optionName)) {
			sb.append(" AND t.option_name = " + optionName);
		}
		if (StringUtils.isNotBlank(optionValue)) {
			sb.append(" AND t.option_value = " + optionValue);
		}
		sb.append(" AND t.dict_id = " + dictId);
		if (StringUtils.isNotBlank(status)) {
			sb.append(" AND t.status = " + status);
		}
		sb.append(" ORDER BY t.option_id");
		String countSql = "select count(*) totalNum from (" + sb.toString() + ") t";
		if (StringUtils.isNotBlank(start) && StringUtils.isNotBlank(length)) {
			sb.append(" limit " + start + "," + length);
		}
		List rows = jdbcTemplate.queryForList(sb.toString());
		dataTablePageUtil.setData(rows);
		int count = Integer.parseInt(jdbcTemplate.queryForList(countSql).get(0).get("totalNum").toString());
		dataTablePageUtil.setRecordsTotal(count);
		dataTablePageUtil.setRecordsFiltered(count);
		return dataTablePageUtil;
	}

	// 保存字典属性
	@POST
	@Path("/option/save")
	public ReturnVO optionSave(DataDictOption option) {
		if (option.getOptionId() != null) { // 更新
			DataDictOption old = optionRepository.findOne(option.getOptionId());
			// 1.前端更改的是optionName
			if (option.getOptionName() != null) {
				List<DataDictOption> existList = optionRepository.findByOptionNameAndDictId(option.getOptionName(),
						option.getDictId());
				if (existList.size() > 1
						|| (existList.size() == 1 && existList.get(0).getOptionId() != option.getOptionId())) {
					return new ReturnVO(0, null, "已经存在相同的属性名称，请重新输入");
				}
				old.setOptionName(option.getOptionName());// 只更新optionName
			}
			// 2.前端要更改的是optionValue
			if (option.getOptionValue() != null) {
				List<DataDictOption> existList = optionRepository.findByOptionValueAndDictId(option.getOptionValue(),
						option.getDictId());
				if (existList.size() > 1
						|| (existList.size() == 1 && existList.get(0).getOptionId() != option.getOptionId())) {
					return new ReturnVO(0, null, "已经存在相同的属性值，请重新输入");
				}
				old.setOptionValue(option.getOptionValue());// 只更新optionValue
			}
			return new ReturnVO(optionRepository.save(old));
		} else { // 新增
			String sql = "select * from t_data_dict_option where (option_name = '" + option.getOptionName()
					+ "' or option_value = '" + option.getOptionValue() + "') and  dict_id = " + option.getDictId();
			List existList = jdbcTemplate.queryForList(sql);
			if (!existList.isEmpty()) {
				return new ReturnVO(0, null, "该字典中已经存在相同的属性名称或者属性值，请重新输入");
			}
			option.setStatus(1);
			return new ReturnVO(optionRepository.save(option));
		}
	}

	// 删除字典属性
	@DELETE
	@Path("/option/del/{optionId}")
	public ReturnVO optionDel(@PathParam("optionId") Long optionId) {
		DataDictOption option = optionRepository.findOne(optionId);
		if (option != null) {
			option.setStatus(-1);
			optionRepository.save(option);
			return new ReturnVO("删除成功");
		} else {
			return new ReturnVO(false, "没有找到要删除的数据");
		}
	}

}